package com.datastructure.test.swaplinkedpair;

public class SwapLinkedPair {

    public static void main(String[] args) {
        SwapLinkedPair swapLinkedPair = new SwapLinkedPair();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next=new ListNode(3);
        head.next.next.next=new ListNode(4);
        head.next.next.next.next=new ListNode(5);
        ListNode listNode = swapLinkedPair.swapLinkedPair(head);
        System.out.println(listNode);
    }

    public ListNode swapLinkedPair (ListNode head) {
        // write code here
        if(head==null||head.next==null){
            return head;
        }
        ListNode last = new ListNode(0);
        ListNode temp = last;
        last.next=head;
        ListNode first = head;
        ListNode second = head.next;
        while (first!=null&&second != null){
            swap(first,second,last);
            last=first;
            first=first.next;
            if(first==null){
                second=null;
            }else {
                second=first.next;
            }
        }
        return temp.next;
    }

    private void swap(ListNode first, ListNode second, ListNode last) {
        first.next=second.next;
        second.next=first;
        last.next=second;
    }
}

class ListNode {
   int val;
   ListNode next = null;
   public ListNode(int val) {
     this.val = val;
   }
 }
